{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 第4篇：索引"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Pandas 数据的索引就像一本书的目录，让我们很快地找到想要看的章节，作为大量数据，创建合理的具有业务意义的索引对我们分析数据至关重要。本篇内容将会带领你学习pandas索引相关的知识。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 认识索引"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "不指定索引的DataFrame\n",
    "![](https://zhangyafei-1258643511.cos.ap-nanjing.myqcloud.com/Python/blog/pandas-index-1.png)\n",
    "指定索引的DataFrame\n",
    "![](https://zhangyafei-1258643511.cos.ap-nanjing.myqcloud.com/Python/blog/pandas-index-2.png)\n",
    "\n",
    "其中：\n",
    "\n",
    "- 行索引是数据的索引，列索引指向的是一个 Series,如果不显式指定，默认为从0开始的序号\n",
    "- DataFrame 的索引也是系列形成的 Series 的索引\n",
    "- 建立索引让数据更加直观明确，如每行数据是针对一个国家的\n",
    "- 建立索引方便数据处理\n",
    "- 索引允许重复，但业务上一般不会让它重复\n",
    "- 有时一个行和列层级较多的数据会出现多层索引 的情况。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**导入所需模块**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pandas as pd"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 建立索引"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 构建DataFrame时指定索引"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "构建DataFrame时不指定索引"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>name</th>\n",
       "      <th>age</th>\n",
       "      <th>city</th>\n",
       "      <th>hobby</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>Tom</td>\n",
       "      <td>18</td>\n",
       "      <td>北京</td>\n",
       "      <td>篮球</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>Bob</td>\n",
       "      <td>30</td>\n",
       "      <td>上海</td>\n",
       "      <td>足球</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>Mary</td>\n",
       "      <td>25</td>\n",
       "      <td>广州</td>\n",
       "      <td>羽毛球</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>James</td>\n",
       "      <td>40</td>\n",
       "      <td>深圳</td>\n",
       "      <td>读书；国学</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>Yafei</td>\n",
       "      <td>20</td>\n",
       "      <td>晋城</td>\n",
       "      <td>篮球；修己</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "    name  age city  hobby\n",
       "0    Tom   18   北京     篮球\n",
       "1    Bob   30   上海     足球\n",
       "2   Mary   25   广州    羽毛球\n",
       "3  James   40   深圳  读书；国学\n",
       "4  Yafei   20   晋城  篮球；修己"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "data = {\n",
    "    \"name\": [\"Tom\", \"Bob\", \"Mary\", \"James\", \"Yafei\"],\n",
    "    \"age\": [18, 30, 25, 40, 20],\n",
    "    \"city\": [\"北京\", \"上海\", \"广州\", \"深圳\", \"晋城\"],\n",
    "    \"hobby\": [\"篮球\", \"足球\", \"羽毛球\", \"读书；国学\", \"篮球；修己\"],\n",
    "}\n",
    "user_info = pd.DataFrame(data=data)\n",
    "user_info"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "构建DataFrame时指定索引"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>age</th>\n",
       "      <th>city</th>\n",
       "      <th>hobby</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>name</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>Tom</th>\n",
       "      <td>18</td>\n",
       "      <td>北京</td>\n",
       "      <td>篮球</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Bob</th>\n",
       "      <td>30</td>\n",
       "      <td>上海</td>\n",
       "      <td>足球</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Mary</th>\n",
       "      <td>25</td>\n",
       "      <td>广州</td>\n",
       "      <td>羽毛球</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>James</th>\n",
       "      <td>40</td>\n",
       "      <td>深圳</td>\n",
       "      <td>读书；国学</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Yafei</th>\n",
       "      <td>20</td>\n",
       "      <td>晋城</td>\n",
       "      <td>篮球；修己</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "       age city  hobby\n",
       "name                  \n",
       "Tom     18   北京     篮球\n",
       "Bob     30   上海     足球\n",
       "Mary    25   广州    羽毛球\n",
       "James   40   深圳  读书；国学\n",
       "Yafei   20   晋城  篮球；修己"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "index = pd.Index(data=[\"Tom\", \"Bob\", \"Mary\", \"James\", \"Yafei\"], name=\"name\")\n",
    "data = {\n",
    "    \"age\": [18, 30, 25, 40, 20],\n",
    "    \"city\": [\"北京\", \"上海\", \"广州\", \"深圳\", \"晋城\"],\n",
    "    \"hobby\": [\"篮球\", \"足球\", \"羽毛球\", \"读书；国学\", \"篮球；修己\"],\n",
    "}\n",
    "user_info = pd.DataFrame(data=data, index=index)\n",
    "user_info"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 读取文件时指定索引"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "读取文件时不指定索引列"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>name</th>\n",
       "      <th>age</th>\n",
       "      <th>city</th>\n",
       "      <th>hobby</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>Tom</td>\n",
       "      <td>18</td>\n",
       "      <td>北京</td>\n",
       "      <td>篮球</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>Bob</td>\n",
       "      <td>30</td>\n",
       "      <td>上海</td>\n",
       "      <td>足球</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>Mary</td>\n",
       "      <td>25</td>\n",
       "      <td>广州</td>\n",
       "      <td>羽毛球</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>James</td>\n",
       "      <td>40</td>\n",
       "      <td>深圳</td>\n",
       "      <td>读书；国学</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>Yafei</td>\n",
       "      <td>20</td>\n",
       "      <td>晋城</td>\n",
       "      <td>篮球；修己</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "    name  age city  hobby\n",
       "0    Tom   18   北京     篮球\n",
       "1    Bob   30   上海     足球\n",
       "2   Mary   25   广州    羽毛球\n",
       "3  James   40   深圳  读书；国学\n",
       "4  Yafei   20   晋城  篮球；修己"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_df = pd.read_excel('data/users.xlsx')\n",
    "user_df"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "读取文件时指定索引列"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>age</th>\n",
       "      <th>city</th>\n",
       "      <th>hobby</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>name</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>Tom</th>\n",
       "      <td>18</td>\n",
       "      <td>北京</td>\n",
       "      <td>篮球</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Bob</th>\n",
       "      <td>30</td>\n",
       "      <td>上海</td>\n",
       "      <td>足球</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Mary</th>\n",
       "      <td>25</td>\n",
       "      <td>广州</td>\n",
       "      <td>羽毛球</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>James</th>\n",
       "      <td>40</td>\n",
       "      <td>深圳</td>\n",
       "      <td>读书；国学</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Yafei</th>\n",
       "      <td>20</td>\n",
       "      <td>晋城</td>\n",
       "      <td>篮球；修己</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "       age city  hobby\n",
       "name                  \n",
       "Tom     18   北京     篮球\n",
       "Bob     30   上海     足球\n",
       "Mary    25   广州    羽毛球\n",
       "James   40   深圳  读书；国学\n",
       "Yafei   20   晋城  篮球；修己"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_df = pd.read_excel('data/users.xlsx',index_col=\"name\")\n",
    "user_df"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 使用set_index设置索引\n",
    ">  set_index(keys, drop=True, append=False, inplace=False, verify_integrity=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>name</th>\n",
       "      <th>age</th>\n",
       "      <th>city</th>\n",
       "      <th>hobby</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>Tom</td>\n",
       "      <td>18</td>\n",
       "      <td>北京</td>\n",
       "      <td>篮球</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>Bob</td>\n",
       "      <td>30</td>\n",
       "      <td>上海</td>\n",
       "      <td>足球</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>Mary</td>\n",
       "      <td>25</td>\n",
       "      <td>广州</td>\n",
       "      <td>羽毛球</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>James</td>\n",
       "      <td>40</td>\n",
       "      <td>深圳</td>\n",
       "      <td>读书；国学</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>Yafei</td>\n",
       "      <td>20</td>\n",
       "      <td>晋城</td>\n",
       "      <td>篮球；修己</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "    name  age city  hobby\n",
       "0    Tom   18   北京     篮球\n",
       "1    Bob   30   上海     足球\n",
       "2   Mary   25   广州    羽毛球\n",
       "3  James   40   深圳  读书；国学\n",
       "4  Yafei   20   晋城  篮球；修己"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "data = {\n",
    "    \"name\": [\"Tom\", \"Bob\", \"Mary\", \"James\", \"Yafei\"],\n",
    "    \"age\": [18, 30, 25, 40, 20],\n",
    "    \"city\": [\"北京\", \"上海\", \"广州\", \"深圳\", \"晋城\"],\n",
    "    \"hobby\": [\"篮球\", \"足球\", \"羽毛球\", \"读书；国学\", \"篮球；修己\"],\n",
    "}\n",
    "user_info = pd.DataFrame(data=data)\n",
    "user_info"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>age</th>\n",
       "      <th>city</th>\n",
       "      <th>hobby</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>name</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>Tom</th>\n",
       "      <td>18</td>\n",
       "      <td>北京</td>\n",
       "      <td>篮球</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Bob</th>\n",
       "      <td>30</td>\n",
       "      <td>上海</td>\n",
       "      <td>足球</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Mary</th>\n",
       "      <td>25</td>\n",
       "      <td>广州</td>\n",
       "      <td>羽毛球</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>James</th>\n",
       "      <td>40</td>\n",
       "      <td>深圳</td>\n",
       "      <td>读书；国学</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Yafei</th>\n",
       "      <td>20</td>\n",
       "      <td>晋城</td>\n",
       "      <td>篮球；修己</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "       age city  hobby\n",
       "name                  \n",
       "Tom     18   北京     篮球\n",
       "Bob     30   上海     足球\n",
       "Mary    25   广州    羽毛球\n",
       "James   40   深圳  读书；国学\n",
       "Yafei   20   晋城  篮球；修己"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 指定索引列\n",
    "user_info.set_index('name')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "利用append参数可以将当前索引维持不变"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th>city</th>\n",
       "      <th>hobby</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>name</th>\n",
       "      <th>age</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>Tom</th>\n",
       "      <th>18</th>\n",
       "      <td>北京</td>\n",
       "      <td>篮球</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Bob</th>\n",
       "      <th>30</th>\n",
       "      <td>上海</td>\n",
       "      <td>足球</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Mary</th>\n",
       "      <th>25</th>\n",
       "      <td>广州</td>\n",
       "      <td>羽毛球</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>James</th>\n",
       "      <th>40</th>\n",
       "      <td>深圳</td>\n",
       "      <td>读书；国学</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Yafei</th>\n",
       "      <th>20</th>\n",
       "      <td>晋城</td>\n",
       "      <td>篮球；修己</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "          city  hobby\n",
       "name  age            \n",
       "Tom   18    北京     篮球\n",
       "Bob   30    上海     足球\n",
       "Mary  25    广州    羽毛球\n",
       "James 40    深圳  读书；国学\n",
       "Yafei 20    晋城  篮球；修己"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_info.set_index('name').set_index(['age'], append=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th>city</th>\n",
       "      <th>hobby</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>name</th>\n",
       "      <th>age</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>Tom</th>\n",
       "      <th>18</th>\n",
       "      <td>北京</td>\n",
       "      <td>篮球</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Bob</th>\n",
       "      <th>30</th>\n",
       "      <td>上海</td>\n",
       "      <td>足球</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Mary</th>\n",
       "      <th>25</th>\n",
       "      <td>广州</td>\n",
       "      <td>羽毛球</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>James</th>\n",
       "      <th>40</th>\n",
       "      <td>深圳</td>\n",
       "      <td>读书；国学</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Yafei</th>\n",
       "      <th>20</th>\n",
       "      <td>晋城</td>\n",
       "      <td>篮球；修己</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "          city  hobby\n",
       "name  age            \n",
       "Tom   18    北京     篮球\n",
       "Bob   30    上海     足球\n",
       "Mary  25    广州    羽毛球\n",
       "James 40    深圳  读书；国学\n",
       "Yafei 20    晋城  篮球；修己"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 指定多个索引列\n",
    "user_info.set_index(['name', 'age'])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**其他的参数**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>name</th>\n",
       "      <th>age</th>\n",
       "      <th>city</th>\n",
       "      <th>hobby</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>name</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>Tom</th>\n",
       "      <td>Tom</td>\n",
       "      <td>18</td>\n",
       "      <td>北京</td>\n",
       "      <td>篮球</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Bob</th>\n",
       "      <td>Bob</td>\n",
       "      <td>30</td>\n",
       "      <td>上海</td>\n",
       "      <td>足球</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Mary</th>\n",
       "      <td>Mary</td>\n",
       "      <td>25</td>\n",
       "      <td>广州</td>\n",
       "      <td>羽毛球</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>James</th>\n",
       "      <td>James</td>\n",
       "      <td>40</td>\n",
       "      <td>深圳</td>\n",
       "      <td>读书；国学</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Yafei</th>\n",
       "      <td>Yafei</td>\n",
       "      <td>20</td>\n",
       "      <td>晋城</td>\n",
       "      <td>篮球；修己</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "        name  age city  hobby\n",
       "name                         \n",
       "Tom      Tom   18   北京     篮球\n",
       "Bob      Bob   30   上海     足球\n",
       "Mary    Mary   25   广州    羽毛球\n",
       "James  James   40   深圳  读书；国学\n",
       "Yafei  Yafei   20   晋城  篮球；修己"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_info.set_index('name', drop=False) # 保留原列"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th>age</th>\n",
       "      <th>city</th>\n",
       "      <th>hobby</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th></th>\n",
       "      <th>name</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <th>Tom</th>\n",
       "      <td>18</td>\n",
       "      <td>北京</td>\n",
       "      <td>篮球</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <th>Bob</th>\n",
       "      <td>30</td>\n",
       "      <td>上海</td>\n",
       "      <td>足球</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <th>Mary</th>\n",
       "      <td>25</td>\n",
       "      <td>广州</td>\n",
       "      <td>羽毛球</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <th>James</th>\n",
       "      <td>40</td>\n",
       "      <td>深圳</td>\n",
       "      <td>读书；国学</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <th>Yafei</th>\n",
       "      <td>20</td>\n",
       "      <td>晋城</td>\n",
       "      <td>篮球；修己</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "         age city  hobby\n",
       "  name                  \n",
       "0 Tom     18   北京     篮球\n",
       "1 Bob     30   上海     足球\n",
       "2 Mary    25   广州    羽毛球\n",
       "3 James   40   深圳  读书；国学\n",
       "4 Yafei   20   晋城  篮球；修己"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_info.set_index('name', append=True) # 保留原来的索引"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>age</th>\n",
       "      <th>city</th>\n",
       "      <th>hobby</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>name</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>Tom</th>\n",
       "      <td>18</td>\n",
       "      <td>北京</td>\n",
       "      <td>篮球</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Bob</th>\n",
       "      <td>30</td>\n",
       "      <td>上海</td>\n",
       "      <td>足球</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Mary</th>\n",
       "      <td>25</td>\n",
       "      <td>广州</td>\n",
       "      <td>羽毛球</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>James</th>\n",
       "      <td>40</td>\n",
       "      <td>深圳</td>\n",
       "      <td>读书；国学</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Yafei</th>\n",
       "      <td>20</td>\n",
       "      <td>晋城</td>\n",
       "      <td>篮球；修己</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "       age city  hobby\n",
       "name                  \n",
       "Tom     18   北京     篮球\n",
       "Bob     30   上海     足球\n",
       "Mary    25   广州    羽毛球\n",
       "James   40   深圳  读书；国学\n",
       "Yafei   20   晋城  篮球；修己"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_info.set_index('name', inplace=True) # 建立索引并重写覆盖\n",
    "user_info"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 通过index属性设置索引"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>age</th>\n",
       "      <th>city</th>\n",
       "      <th>hobby</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>name</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>Tom</th>\n",
       "      <td>18</td>\n",
       "      <td>北京</td>\n",
       "      <td>篮球</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Bob</th>\n",
       "      <td>30</td>\n",
       "      <td>上海</td>\n",
       "      <td>足球</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Mary</th>\n",
       "      <td>25</td>\n",
       "      <td>广州</td>\n",
       "      <td>羽毛球</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>James</th>\n",
       "      <td>40</td>\n",
       "      <td>深圳</td>\n",
       "      <td>读书；国学</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Yafei</th>\n",
       "      <td>20</td>\n",
       "      <td>晋城</td>\n",
       "      <td>篮球；修己</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "       age city  hobby\n",
       "name                  \n",
       "Tom     18   北京     篮球\n",
       "Bob     30   上海     足球\n",
       "Mary    25   广州    羽毛球\n",
       "James   40   深圳  读书；国学\n",
       "Yafei   20   晋城  篮球；修己"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "data = {\n",
    "    \"age\": [18, 30, 25, 40, 20],\n",
    "    \"city\": [\"北京\", \"上海\", \"广州\", \"深圳\", \"晋城\"],\n",
    "    \"hobby\": [\"篮球\", \"足球\", \"羽毛球\", \"读书；国学\", \"篮球；修己\"],\n",
    "}\n",
    "user_info = pd.DataFrame(data=data)\n",
    "user_info.index = pd.Index(data=[\"Tom\", \"Bob\", \"Mary\", \"James\", \"Yafei\"], name=\"name\")\n",
    "user_info"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 重置索引\n",
    "\n",
    "有时我们想取消已有的索引，以重新来过，可以使用 reset_index()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>name</th>\n",
       "      <th>age</th>\n",
       "      <th>city</th>\n",
       "      <th>hobby</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>Tom</td>\n",
       "      <td>18</td>\n",
       "      <td>北京</td>\n",
       "      <td>篮球</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>Bob</td>\n",
       "      <td>30</td>\n",
       "      <td>上海</td>\n",
       "      <td>足球</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>Mary</td>\n",
       "      <td>25</td>\n",
       "      <td>广州</td>\n",
       "      <td>羽毛球</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>James</td>\n",
       "      <td>40</td>\n",
       "      <td>深圳</td>\n",
       "      <td>读书；国学</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>Yafei</td>\n",
       "      <td>20</td>\n",
       "      <td>晋城</td>\n",
       "      <td>篮球；修己</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "    name  age city  hobby\n",
       "0    Tom   18   北京     篮球\n",
       "1    Bob   30   上海     足球\n",
       "2   Mary   25   广州    羽毛球\n",
       "3  James   40   深圳  读书；国学\n",
       "4  Yafei   20   晋城  篮球；修己"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_info.reset_index()  # 清除索引 \n",
    "# user_info.reset_index(inploace=True) # 覆盖使生效"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>age</th>\n",
       "      <th>city</th>\n",
       "      <th>hobby</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>18</td>\n",
       "      <td>北京</td>\n",
       "      <td>篮球</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>30</td>\n",
       "      <td>上海</td>\n",
       "      <td>足球</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>25</td>\n",
       "      <td>广州</td>\n",
       "      <td>羽毛球</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>40</td>\n",
       "      <td>深圳</td>\n",
       "      <td>读书；国学</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>20</td>\n",
       "      <td>晋城</td>\n",
       "      <td>篮球；修己</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   age city  hobby\n",
       "0   18   北京     篮球\n",
       "1   30   上海     足球\n",
       "2   25   广州    羽毛球\n",
       "3   40   深圳  读书；国学\n",
       "4   20   晋城  篮球；修己"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 删除原索引，name 列没了\n",
    "user_info.reset_index().set_index('name').reset_index(drop=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "多级索引"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th>city</th>\n",
       "      <th>hobby</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>name</th>\n",
       "      <th>age</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>Tom</th>\n",
       "      <th>18</th>\n",
       "      <td>北京</td>\n",
       "      <td>篮球</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Bob</th>\n",
       "      <th>30</th>\n",
       "      <td>上海</td>\n",
       "      <td>足球</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Mary</th>\n",
       "      <th>25</th>\n",
       "      <td>广州</td>\n",
       "      <td>羽毛球</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>James</th>\n",
       "      <th>40</th>\n",
       "      <td>深圳</td>\n",
       "      <td>读书；国学</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Yafei</th>\n",
       "      <th>20</th>\n",
       "      <td>晋城</td>\n",
       "      <td>篮球；修己</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "          city  hobby\n",
       "name  age            \n",
       "Tom   18    北京     篮球\n",
       "Bob   30    上海     足球\n",
       "Mary  25    广州    羽毛球\n",
       "James 40    深圳  读书；国学\n",
       "Yafei 20    晋城  篮球；修己"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_info.set_index('age', append=True, inplace=True)\n",
    "user_info"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>name</th>\n",
       "      <th>age</th>\n",
       "      <th>city</th>\n",
       "      <th>hobby</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>Tom</td>\n",
       "      <td>18</td>\n",
       "      <td>北京</td>\n",
       "      <td>篮球</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>Bob</td>\n",
       "      <td>30</td>\n",
       "      <td>上海</td>\n",
       "      <td>足球</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>Mary</td>\n",
       "      <td>25</td>\n",
       "      <td>广州</td>\n",
       "      <td>羽毛球</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>James</td>\n",
       "      <td>40</td>\n",
       "      <td>深圳</td>\n",
       "      <td>读书；国学</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>Yafei</td>\n",
       "      <td>20</td>\n",
       "      <td>晋城</td>\n",
       "      <td>篮球；修己</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "    name  age city  hobby\n",
       "0    Tom   18   北京     篮球\n",
       "1    Bob   30   上海     足球\n",
       "2   Mary   25   广州    羽毛球\n",
       "3  James   40   深圳  读书；国学\n",
       "4  Yafei   20   晋城  篮球；修己"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_info.reset_index()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>age</th>\n",
       "      <th>city</th>\n",
       "      <th>hobby</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>name</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>Tom</th>\n",
       "      <td>18</td>\n",
       "      <td>北京</td>\n",
       "      <td>篮球</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Bob</th>\n",
       "      <td>30</td>\n",
       "      <td>上海</td>\n",
       "      <td>足球</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Mary</th>\n",
       "      <td>25</td>\n",
       "      <td>广州</td>\n",
       "      <td>羽毛球</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>James</th>\n",
       "      <td>40</td>\n",
       "      <td>深圳</td>\n",
       "      <td>读书；国学</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Yafei</th>\n",
       "      <td>20</td>\n",
       "      <td>晋城</td>\n",
       "      <td>篮球；修己</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "       age city  hobby\n",
       "name                  \n",
       "Tom     18   北京     篮球\n",
       "Bob     30   上海     足球\n",
       "Mary    25   广州    羽毛球\n",
       "James   40   深圳  读书；国学\n",
       "Yafei   20   晋城  篮球；修己"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_info.reset_index(level=1) # 使用层级索引序号"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>name</th>\n",
       "      <th>city</th>\n",
       "      <th>hobby</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>age</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>18</th>\n",
       "      <td>Tom</td>\n",
       "      <td>北京</td>\n",
       "      <td>篮球</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>30</th>\n",
       "      <td>Bob</td>\n",
       "      <td>上海</td>\n",
       "      <td>足球</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>25</th>\n",
       "      <td>Mary</td>\n",
       "      <td>广州</td>\n",
       "      <td>羽毛球</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>40</th>\n",
       "      <td>James</td>\n",
       "      <td>深圳</td>\n",
       "      <td>读书；国学</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>20</th>\n",
       "      <td>Yafei</td>\n",
       "      <td>晋城</td>\n",
       "      <td>篮球；修己</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "      name city  hobby\n",
       "age                   \n",
       "18     Tom   北京     篮球\n",
       "30     Bob   上海     足球\n",
       "25    Mary   广州    羽毛球\n",
       "40   James   深圳  读书；国学\n",
       "20   Yafei   晋城  篮球；修己"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_info.reset_index(level='name') # 使用层级索引名"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 修改索引"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 修改索引名"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "rename_axis是针对多级索引的方法，作用是修改某一层的索引名，而不是索引标签"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th>city</th>\n",
       "      <th>hobby</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>姓名</th>\n",
       "      <th>年龄</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>Tom</th>\n",
       "      <th>18</th>\n",
       "      <td>北京</td>\n",
       "      <td>篮球</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Bob</th>\n",
       "      <th>30</th>\n",
       "      <td>上海</td>\n",
       "      <td>足球</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Mary</th>\n",
       "      <th>25</th>\n",
       "      <td>广州</td>\n",
       "      <td>羽毛球</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>James</th>\n",
       "      <th>40</th>\n",
       "      <td>深圳</td>\n",
       "      <td>读书；国学</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Yafei</th>\n",
       "      <th>20</th>\n",
       "      <td>晋城</td>\n",
       "      <td>篮球；修己</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "         city  hobby\n",
       "姓名    年龄            \n",
       "Tom   18   北京     篮球\n",
       "Bob   30   上海     足球\n",
       "Mary  25   广州    羽毛球\n",
       "James 40   深圳  读书；国学\n",
       "Yafei 20   晋城  篮球；修己"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_info.rename_axis(index={'name': '姓名', 'age': '年龄'})"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 修改索引标签\n",
    "rename方法用于修改列或者行索引标签，而不是索引名："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th>城市</th>\n",
       "      <th>hobby</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>name</th>\n",
       "      <th>age</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>汤姆</th>\n",
       "      <th>18</th>\n",
       "      <td>北京</td>\n",
       "      <td>篮球</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Bob</th>\n",
       "      <th>30</th>\n",
       "      <td>上海</td>\n",
       "      <td>足球</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Mary</th>\n",
       "      <th>25</th>\n",
       "      <td>广州</td>\n",
       "      <td>羽毛球</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>James</th>\n",
       "      <th>40</th>\n",
       "      <td>深圳</td>\n",
       "      <td>读书；国学</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Yafei</th>\n",
       "      <th>20</th>\n",
       "      <td>晋城</td>\n",
       "      <td>篮球；修己</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "           城市  hobby\n",
       "name  age           \n",
       "汤姆    18   北京     篮球\n",
       "Bob   30   上海     足球\n",
       "Mary  25   广州    羽毛球\n",
       "James 40   深圳  读书；国学\n",
       "Yafei 20   晋城  篮球；修己"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_info.rename(index={'Tom': '汤姆'}, columns={'city': '城市'})"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 索引类型"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "为了适应各种业务数据的处理，索引又针对各种类型数据定义了不同的索引类型："
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 数字索引 Numeric Index\n",
    "共有以下几种：\n",
    "\n",
    "- RangeIndex: 单调整数范围的不可变索引。\n",
    "- Int64Index: int64类型，有序可切片集合的不可变ndarray。\n",
    "- UInt64Index: 无符号整数标签的\n",
    "- Float64Index: Float64 类型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "RangeIndex(start=1, stop=100, step=2)"
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pd.RangeIndex(1,100,2)\n",
    "# RangeIndex(start=1, stop=100, step=2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Int64Index([1, 2, 3, -4], dtype='int64', name='num')"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pd.Int64Index([1,2,3,-4], name='num')\n",
    "# Int64Index([1, 2, 3, -4], dtype='int64', name='num')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "UInt64Index([1, 2, 3, 4], dtype='uint64')"
      ]
     },
     "execution_count": 24,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pd.UInt64Index([1,2,3,4])\n",
    "# UInt64Index([1, 2, 3, 4], dtype='uint64')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Float64Index([1.2, 2.3, 3.0, 4.0], dtype='float64')"
      ]
     },
     "execution_count": 25,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pd.Float64Index([1.2,2.3,3,4])\n",
    "# Float64Index([1.2, 2.3, 3.0, 4.0], dtype='float64')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 类别索引 CategoricalIndex\n",
    "\n",
    "类别只能包含有限数量的（通常是固定的）可能值（类别）。 可以理解成枚举，比如性别只有男女，但在数据中每行都有，如果按文本处理会效率不高。  \n",
    "类别的底层是 pandas.Categorical。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "CategoricalIndex(['a', 'b', 'a', 'b'], categories=['a', 'b'], ordered=False, dtype='category')"
      ]
     },
     "execution_count": 26,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pd.CategoricalIndex(['a', 'b', 'a', 'b'])\n",
    "# CategoricalIndex(['a', 'b', 'a', 'b'], categories=['a', 'b'], ordered=False, dtype='category')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "类别后边后有专门的讲解，只有在体量非常大的数据面前才能显示其优势。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 间隔索引 IntervalIndex"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "\"\\nIntervalIndex([(0, 1], (1, 2], (2, 3], (3, 4], (4, 5]],\\n              closed='right',\\n              dtype='interval[int64]')\\n\""
      ]
     },
     "execution_count": 27,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pd.interval_range(start=0, end=5)\n",
    "'''\n",
    "IntervalIndex([(0, 1], (1, 2], (2, 3], (3, 4], (4, 5]],\n",
    "              closed='right',\n",
    "              dtype='interval[int64]')\n",
    "'''"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 多层索引 MultiIndex\n",
    "教程后边会有专门的讲解。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "\"\\nMultiIndex([(1,  'red'),\\n            (1, 'blue'),\\n            (2,  'red'),\\n            (2, 'blue')],\\n           names=['number', 'color'])\\n\""
      ]
     },
     "execution_count": 28,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "arrays = [[1, 1, 2, 2], ['red', 'blue', 'red', 'blue']]\n",
    "pd.MultiIndex.from_arrays(arrays, names=('number', 'color'))\n",
    "'''\n",
    "MultiIndex([(1,  'red'),\n",
    "            (1, 'blue'),\n",
    "            (2,  'red'),\n",
    "            (2, 'blue')],\n",
    "           names=['number', 'color'])\n",
    "'''"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 时间索引 DatetimeIndex"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "DatetimeIndex(['2018-01-01', '2018-01-02', '2018-01-03', '2018-01-04',\n",
       "               '2018-01-05', '2018-01-06', '2018-01-07', '2018-01-08'],\n",
       "              dtype='datetime64[ns]', freq='D')"
      ]
     },
     "execution_count": 29,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pd.date_range(start='1/1/2018', end='1/08/2018')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "DatetimeIndex(['2018-01-01', '2018-01-02', '2018-01-03', '2018-01-04',\n",
       "               '2018-01-05', '2018-01-06', '2018-01-07', '2018-01-08'],\n",
       "              dtype='datetime64[ns]', freq='D')"
      ]
     },
     "execution_count": 30,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 指定开始时间和周期\n",
    "pd.date_range(start='1/1/2018', periods=8)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "PeriodIndex(['2017-01', '2017-02', '2017-03', '2017-04', '2017-05', '2017-06',\n",
       "             '2017-07', '2017-08', '2017-09', '2017-10', '2017-11', '2017-12',\n",
       "             '2018-01'],\n",
       "            dtype='period[M]', freq='M')"
      ]
     },
     "execution_count": 31,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 以月为周期\n",
    "pd.period_range(start='2017-01-01', end='2018-01-01', freq='M')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "PeriodIndex(['2017-03', '2017-04', '2017-05', '2017-06'], dtype='period[M]', freq='M')"
      ]
     },
     "execution_count": 32,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 周期嵌套\n",
    "pd.period_range(start=pd.Period('2017Q1', freq='Q'),\n",
    "                end=pd.Period('2017Q2', freq='Q'), freq='M')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 时间差 TimedeltaIndex"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "TimedeltaIndex([    '0 days 06:05:01.000030',     '0 days 23:59:59.999999',\n",
       "                '22 days 00:02:00.000003010',     '0 days 23:29:59.999999',\n",
       "                    '0 days 12:19:59.999999'],\n",
       "               dtype='timedelta64[ns]', freq=None)"
      ]
     },
     "execution_count": 33,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pd.TimedeltaIndex(data =['06:05:01.000030', '+23:59:59.999999',\n",
    "                         '22 day 2 min 3us 10ns', '+23:29:59.999999',\n",
    "                         '+12:19:59.999999'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "TimedeltaIndex(['1 days 00:00:00', '1 days 00:00:05', '2 days 00:00:00',\n",
       "                '2 days 00:00:02'],\n",
       "               dtype='timedelta64[ns]', freq=None)"
      ]
     },
     "execution_count": 34,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 使用 datetime\n",
    "import datetime\n",
    "pd.TimedeltaIndex(['1 days', '1 days, 00:00:05',\n",
    "                   np.timedelta64(2, 'D'),\n",
    "                   datetime.timedelta(days=2, seconds=2)])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 周期索引 PeriodIndex"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "PeriodIndex(['2021-01-21 10:00:05', '2021-01-21 10:00:06',\n",
       "             '2021-01-21 10:00:07', '2021-01-21 10:00:08',\n",
       "             '2021-01-21 10:00:09', '2021-01-21 10:00:10',\n",
       "             '2021-01-21 10:00:11', '2021-01-21 10:00:12'],\n",
       "            dtype='period[S]', freq='S')"
      ]
     },
     "execution_count": 35,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "t = pd.period_range('2021-1-21 10:00:05', periods=8, freq='S')\n",
    "pd.PeriodIndex(t,freq='S')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 索引对象\n",
    "行和列的索引在 Pandas 里其实是一个 Index 对象，以下是创建一个 index 对象的方法："
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 创建对象"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Int64Index([1, 2, 3], dtype='int64')"
      ]
     },
     "execution_count": 36,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pd.Index([1, 2, 3])\n",
    "# Int64Index([1, 2, 3], dtype='int64')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Index(['a', 'b', 'c'], dtype='object')"
      ]
     },
     "execution_count": 37,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pd.Index(list('abc'))\n",
    "# Index(['a', 'b', 'c'], dtype='object')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Index(['e', 'd', 'a', 'b'], dtype='object', name='something')"
      ]
     },
     "execution_count": 38,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 可以定义一相 name\n",
    "pd.Index(['e', 'd', 'a', 'b'], name='something')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 查看"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th>city</th>\n",
       "      <th>hobby</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>name</th>\n",
       "      <th>age</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>Tom</th>\n",
       "      <th>18</th>\n",
       "      <td>北京</td>\n",
       "      <td>篮球</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Bob</th>\n",
       "      <th>30</th>\n",
       "      <td>上海</td>\n",
       "      <td>足球</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Mary</th>\n",
       "      <th>25</th>\n",
       "      <td>广州</td>\n",
       "      <td>羽毛球</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>James</th>\n",
       "      <th>40</th>\n",
       "      <td>深圳</td>\n",
       "      <td>读书；国学</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Yafei</th>\n",
       "      <th>20</th>\n",
       "      <td>晋城</td>\n",
       "      <td>篮球；修己</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "          city  hobby\n",
       "name  age            \n",
       "Tom   18    北京     篮球\n",
       "Bob   30    上海     足球\n",
       "Mary  25    广州    羽毛球\n",
       "James 40    深圳  读书；国学\n",
       "Yafei 20    晋城  篮球；修己"
      ]
     },
     "execution_count": 39,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df = user_info\n",
    "df"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "MultiIndex([(  'Tom', 18),\n",
       "            (  'Bob', 30),\n",
       "            ( 'Mary', 25),\n",
       "            ('James', 40),\n",
       "            ('Yafei', 20)],\n",
       "           names=['name', 'age'])"
      ]
     },
     "execution_count": 40,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df.index"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Index(['city', 'hobby'], dtype='object')"
      ]
     },
     "execution_count": 41,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df.columns"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 属性\n",
    "\n",
    "以下方法也适用于 df.columns, 因为都是 index 对象：\n",
    "- df.index.name # 名称\n",
    "- df.index.array: array 数组\n",
    "- df.index.dtype: 数据类型\n",
    "- df.index.shape: 形状\n",
    "- df.index.size: 元素数量\n",
    "- df.index.values: array 数组\n",
    "其他，不常用\n",
    "- df.index.empty: 是否为空\n",
    "- df.index.is_unique: 是否不重复\n",
    "- df.index.names: 名称列表\n",
    "- df.index.is_all_dates: 是否全是日期时间\n",
    "- df.index.has_duplicates: 是否有重复值\n",
    "- df.index.values: 索引的值 array"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 操作\n",
    "以下方法也适用于 - df.columns, 因为都是 index 对象，有些也支持 Series：\n",
    "\n",
    "**基本方法** \n",
    "- df.index.astype('int64'): 转换类型\n",
    "- df.index.isin(): 是否存在，见下方示例\n",
    "- df.index.rename('number'): 修改索引名称\n",
    "- df.index.nunique(): 不重复值的数量\n",
    "- df.index.sort_values(ascending=False,): 排序,倒序\n",
    "- df.index.map(lambda x:x+'_'): map 函数处理\n",
    "- df.index.str.replace('_', ''): str 替换\n",
    "- df.index.str.split('_'): 分隔\n",
    "- df.index.to_list(): 转为列表\n",
    "- df.index.to_frame(index=False, name='a'): 转成 DataFrame\n",
    "- df.index.to_series(): 转 series\n",
    "- df.index.to_numpy(): 转为 numpy\n",
    "- df.index.unique(): 去重\n",
    "- df.index.value_counts(): 去重及数量\n",
    "- df.index.where(- df.index=='a'): 筛选\n",
    "- df.index.rename('grade', inplace=False): 重命名索引名称\n",
    "- df.index.rename(['species', 'year']): 多层，重命名索引名称\n",
    "- df.index.max(): 最大值\n",
    "- df.index.argmax(): 最大索引值\n",
    "- df.index.any()\n",
    "- df.index.all()\n",
    "- df.index.T: 转置，多层索引里很有用\n",
    "\n",
    "**其他，不常用**\n",
    "- df.index.append(pd.Index([4,5])): 追加\n",
    "- df.index.repeat(2): 重复几次\n",
    "- df.index.inferred_type: 推测数据类型\n",
    "- df.index.hasnans: 有没有空值\n",
    "- df.index.is_monotonic_decreasing: 是否单调递减\n",
    "- df.index.is_monotonic: 是否单调递增\n",
    "- df.index.is_monotonic_increasing: 是否单调递增\n",
    "- df.index.nbytes: 基础数据中的字节数\n",
    "- df.index.ndim: 维度数，维数\n",
    "- df.index.nlevels: 索引层级数，通常为 1\n",
    "- df.index.min(): 最小值\n",
    "- df.index.argmin(): 最小索引值\n",
    "- df.index.argsort(): 顺序值组成的数组\n",
    "- df.index.asof(2): 返回最近的索引\n",
    "\n",
    "**拷贝**\n",
    "- df.index.astype('int64', copy=True): 深拷贝\n",
    "- df.index.copy(name='new', deep=True, dtype='int64')\n",
    "\n",
    "**删除指定位置**\n",
    "- df.index.delete(1): 删除指定位置\n",
    "\n",
    "**对比不同**\n",
    "- df.index.difference(pd.Index([1,2,4]), sort=False)\n",
    "- df.index.drop('a', errors='ignore'): 删除\n",
    "- df.index.drop_duplicates(keep='first'): 去重值\n",
    "- df.index.droplevel(0): 删除层级\n",
    "- df.index.dropna(how='all'): 删除空值\n",
    "- df.index.duplicated(keep='first'): 重复值在结果数组中为True\n",
    "- df.index.equals(- df.index): 与另外一个索引对象是否相同\n",
    "- df.index.factorize(): 分解成（array:0-n, Index）\n",
    "- df.index.fillna(0, {0:'nan'}): 填充空值\n",
    "\n",
    "**字符列表, 把 name 值加在第一位, 每个值加10**\n",
    "- df.index.format(name=True, formatter=lambda x:x+10)\n",
    "\n",
    "**返回一个 array, 指定值的索引位数组，不在的为 -1**\n",
    "- df.index.get_indexer([2,9])\n",
    "\n",
    "**获取 指定层级 Index 对象**\n",
    "- df.index.get_level_values(0)\n",
    "\n",
    "**指定索引的位置**\n",
    "- df.index.get_loc('b')\n",
    "- df.index.insert(2, 'f'): 在索引位 2 插入 f\n",
    "- df.index.intersection(- df.index): 交集\n",
    "- df.index.is_(- df.index): 类似 is 检查\n",
    "- df.index.is_categorical(): 是否分类数据\n",
    "- df.index.is_type_compatible(- df.index): 类型是否兼容\n",
    "- df.index.is_type_compatible(1): 类型是否兼容\n",
    "\n",
    "- df.index.isna(): array 是否为空\n",
    "- df.index.isnull(): array 是否缺失值\n",
    "- df.index.join(- df.index, how='left'): 连接\n",
    "- df.index.notna(): 是否不存在的值\n",
    "- df.index.notnull(): 是否不存在的值\n",
    "- df.index.ravel(): 展平值的ndarray\n",
    "- df.index.reindex(['a','b']): 新索引 (Index,array:0-n)\n",
    "- df.index.searchsorted('f'): 如果插入这个值排序后在哪个索引位\n",
    "- df.index.searchsorted([0, 4]): array([0, 3]) 多个\n",
    "- df.index.set_names('quarter'): 设置索引名称\n",
    "- df.index.set_names('species', level=0)\n",
    "- df.index.set_names(['kind', 'year'], inplace=True)\n",
    "- df.index.shift(10, freq='D'): 日期索引向前移动 10 天\n",
    "- idx1.symmetric_difference(idx2): 两个索引不同的内容\n",
    "- idx1.union(idx2): 拼接\n",
    "\n",
    "- df.add_prefix('t_'): 表头加前缀\n",
    "- df.add_suffix('_d'): 表头加后缀\n",
    "- df.first_valid_index(): 第一个有值的索引\n",
    "- df.last_valid_index(): 最后一个有值的索引"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 重复索引\n",
    "注：Pandas 版本要求 1.2.0+，这是一项实验功能\n",
    "\n",
    "Pandas 默认地行列索引对象不需要唯一，可以有重复的行或列标签。但有时候比如通过 SQL 将数据存入数据库，就不能有重复的索引和列名，我们可以通过设置来限制重复索引："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "metadata": {},
   "outputs": [],
   "source": [
    "# df = pd.DataFrame({\"A\": [1, 2]}, index=['a', 'a'])\n",
    "# df"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 默认是允许重复的\n",
    "# df.flags[\"allows_duplicate_labels\"] # True\n",
    "# df.flags.allows_duplicate_labels # True\n",
    "# df.flags\n",
    "# <Flags(allows_duplicate_labels=True)>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "metadata": {},
   "outputs": [],
   "source": [
    "# # 已重复的就不能再设置为不重复的了\n",
    "# df.flags.allows_duplicate_labels = False\n",
    "# # DuplicateLabelError: Index has duplicates. positions....\n",
    "\n",
    "# # 生成时设置为标签为不可重复，后继操作就不能有重复的索引了\n",
    "# s = (pd.Series([1, 2], index=['a', 'b'])\n",
    "#  .set_flags(allows_duplicate_labels=False)\n",
    "# )\n",
    "# s.reindex(['a', 'a'])\n",
    "# DuplicateLabelError: Index has duplicates..."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 多级索引\n",
    "多级索引（也称层次化索引）是pandas的重要功能，可以在Series、DataFrame对象上拥有2个以及2个以上的索引。\n",
    "实质上，单级索引对应Index对象,多级索引对应MultiIndex对象。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### series对象的多级索引"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 创建"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "a  1   -0.829829\n",
       "   2   -0.344319\n",
       "b  1   -0.495467\n",
       "   2    1.672378\n",
       "dtype: float64"
      ]
     },
     "execution_count": 45,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "se1=pd.Series(np.random.randn(4),index=[list(\"aabb\"),[1,2,1,2]])\n",
    "se1"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 子集的选取"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1   -0.829829\n",
       "2   -0.344319\n",
       "dtype: float64"
      ]
     },
     "execution_count": 46,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "se1['a']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "a  1   -0.829829\n",
       "   2   -0.344319\n",
       "b  1   -0.495467\n",
       "   2    1.672378\n",
       "dtype: float64"
      ]
     },
     "execution_count": 47,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "se1['a': 'b']"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 内层选取"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "a   -0.829829\n",
       "b   -0.495467\n",
       "dtype: float64"
      ]
     },
     "execution_count": 48,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "se1[:, 1]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "a   -0.344319\n",
       "b    1.672378\n",
       "dtype: float64"
      ]
     },
     "execution_count": 49,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "se1[:, 2]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### DataFrame的多级索引"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 创建多层行索引"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 隐式构造: 列表套列表"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th>语文</th>\n",
       "      <th>数学</th>\n",
       "      <th>Python</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th rowspan=\"2\" valign=\"top\">Michal</th>\n",
       "      <th>Mid</th>\n",
       "      <td>17</td>\n",
       "      <td>113</td>\n",
       "      <td>134</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>End</th>\n",
       "      <td>63</td>\n",
       "      <td>141</td>\n",
       "      <td>147</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th rowspan=\"2\" valign=\"top\">Kobe</th>\n",
       "      <th>Mid</th>\n",
       "      <td>4</td>\n",
       "      <td>107</td>\n",
       "      <td>99</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>End</th>\n",
       "      <td>13</td>\n",
       "      <td>46</td>\n",
       "      <td>12</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th rowspan=\"2\" valign=\"top\">James</th>\n",
       "      <th>Mid</th>\n",
       "      <td>33</td>\n",
       "      <td>38</td>\n",
       "      <td>28</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>End</th>\n",
       "      <td>44</td>\n",
       "      <td>36</td>\n",
       "      <td>88</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "            语文   数学  Python\n",
       "Michal Mid  17  113     134\n",
       "       End  63  141     147\n",
       "Kobe   Mid   4  107      99\n",
       "       End  13   46      12\n",
       "James  Mid  33   38      28\n",
       "       End  44   36      88"
      ]
     },
     "execution_count": 50,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df = pd.DataFrame(np.random.randint(0, 150, size=(6,3)), columns=['语文', '数学', 'Python'], index=[['Michal', 'Michal', 'Kobe','Kobe', 'James', 'James'],['Mid','End', 'Mid', 'End','Mid', 'End']])\n",
    "df"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 显式构造"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**from_arrays**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th>语文</th>\n",
       "      <th>数学</th>\n",
       "      <th>Python</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th rowspan=\"2\" valign=\"top\">Michal</th>\n",
       "      <th>Mid</th>\n",
       "      <td>145</td>\n",
       "      <td>66</td>\n",
       "      <td>14</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>End</th>\n",
       "      <td>0</td>\n",
       "      <td>67</td>\n",
       "      <td>113</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th rowspan=\"2\" valign=\"top\">Kobe</th>\n",
       "      <th>Mid</th>\n",
       "      <td>147</td>\n",
       "      <td>122</td>\n",
       "      <td>141</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>End</th>\n",
       "      <td>2</td>\n",
       "      <td>31</td>\n",
       "      <td>71</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th rowspan=\"2\" valign=\"top\">James</th>\n",
       "      <th>Mid</th>\n",
       "      <td>8</td>\n",
       "      <td>56</td>\n",
       "      <td>88</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>End</th>\n",
       "      <td>76</td>\n",
       "      <td>109</td>\n",
       "      <td>124</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "             语文   数学  Python\n",
       "Michal Mid  145   66      14\n",
       "       End    0   67     113\n",
       "Kobe   Mid  147  122     141\n",
       "       End    2   31      71\n",
       "James  Mid    8   56      88\n",
       "       End   76  109     124"
      ]
     },
     "execution_count": 51,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 使用数组\n",
    "df = pd.DataFrame(np.random.randint(0, 150, size=(6,3)), columns=['语文', '数学', 'Python'], index=pd.MultiIndex.from_arrays([['Michal', 'Michal', 'Kobe','Kobe', 'James', 'James'],['Mid','End', 'Mid', 'End','Mid', 'End']]))\n",
    "df"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**from_tuples**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th>语文</th>\n",
       "      <th>数学</th>\n",
       "      <th>Python</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th rowspan=\"2\" valign=\"top\">Michal</th>\n",
       "      <th>期中</th>\n",
       "      <td>65</td>\n",
       "      <td>17</td>\n",
       "      <td>98</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>期末</th>\n",
       "      <td>21</td>\n",
       "      <td>29</td>\n",
       "      <td>118</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th rowspan=\"2\" valign=\"top\">Kobe</th>\n",
       "      <th>期中</th>\n",
       "      <td>51</td>\n",
       "      <td>37</td>\n",
       "      <td>70</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>期末</th>\n",
       "      <td>35</td>\n",
       "      <td>57</td>\n",
       "      <td>6</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th rowspan=\"2\" valign=\"top\">James</th>\n",
       "      <th>期中</th>\n",
       "      <td>145</td>\n",
       "      <td>125</td>\n",
       "      <td>139</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>期末</th>\n",
       "      <td>36</td>\n",
       "      <td>132</td>\n",
       "      <td>68</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "            语文   数学  Python\n",
       "Michal 期中   65   17      98\n",
       "       期末   21   29     118\n",
       "Kobe   期中   51   37      70\n",
       "       期末   35   57       6\n",
       "James  期中  145  125     139\n",
       "       期末   36  132      68"
      ]
     },
     "execution_count": 52,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 使用元组\n",
    "df = pd.DataFrame(np.random.randint(0, 150, size=(6,3)), columns=['语文', '数学', 'Python'], index=pd.MultiIndex.from_tuples([('Michal','期中'), ('Michal','期末'), ('Kobe','期中'), ('Kobe','期末'), ('James','期中'), ('James','期末')]))\n",
    "df"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**from_product**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th>语文</th>\n",
       "      <th>数学</th>\n",
       "      <th>Python</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th rowspan=\"2\" valign=\"top\">Michal</th>\n",
       "      <th>Mid</th>\n",
       "      <td>63</td>\n",
       "      <td>61</td>\n",
       "      <td>85</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>End</th>\n",
       "      <td>133</td>\n",
       "      <td>71</td>\n",
       "      <td>27</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th rowspan=\"2\" valign=\"top\">Kobe</th>\n",
       "      <th>Mid</th>\n",
       "      <td>133</td>\n",
       "      <td>72</td>\n",
       "      <td>132</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>End</th>\n",
       "      <td>60</td>\n",
       "      <td>115</td>\n",
       "      <td>15</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th rowspan=\"2\" valign=\"top\">James</th>\n",
       "      <th>Mid</th>\n",
       "      <td>146</td>\n",
       "      <td>128</td>\n",
       "      <td>129</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>End</th>\n",
       "      <td>10</td>\n",
       "      <td>110</td>\n",
       "      <td>9</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "             语文   数学  Python\n",
       "Michal Mid   63   61      85\n",
       "       End  133   71      27\n",
       "Kobe   Mid  133   72     132\n",
       "       End   60  115      15\n",
       "James  Mid  146  128     129\n",
       "       End   10  110       9"
      ]
     },
     "execution_count": 53,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 使用product\n",
    "df = pd.DataFrame(np.random.randint(0, 150, size=(6,3)), columns=['语文', '数学', 'Python'], index=pd.MultiIndex.from_product([['Michal','Kobe','James'],['Mid','End']]))\n",
    "df"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 指定df中的列创建（set_index方法）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 54,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>姓名</th>\n",
       "      <th>学期</th>\n",
       "      <th>语文</th>\n",
       "      <th>数学</th>\n",
       "      <th>Python</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>Michal</td>\n",
       "      <td>Mid</td>\n",
       "      <td>63</td>\n",
       "      <td>61</td>\n",
       "      <td>85</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>Michal</td>\n",
       "      <td>End</td>\n",
       "      <td>133</td>\n",
       "      <td>71</td>\n",
       "      <td>27</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>Kobe</td>\n",
       "      <td>Mid</td>\n",
       "      <td>133</td>\n",
       "      <td>72</td>\n",
       "      <td>132</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>Kobe</td>\n",
       "      <td>End</td>\n",
       "      <td>60</td>\n",
       "      <td>115</td>\n",
       "      <td>15</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>James</td>\n",
       "      <td>Mid</td>\n",
       "      <td>146</td>\n",
       "      <td>128</td>\n",
       "      <td>129</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>James</td>\n",
       "      <td>End</td>\n",
       "      <td>10</td>\n",
       "      <td>110</td>\n",
       "      <td>9</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "       姓名   学期   语文   数学  Python\n",
       "0  Michal  Mid   63   61      85\n",
       "1  Michal  End  133   71      27\n",
       "2    Kobe  Mid  133   72     132\n",
       "3    Kobe  End   60  115      15\n",
       "4   James  Mid  146  128     129\n",
       "5   James  End   10  110       9"
      ]
     },
     "execution_count": 54,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df.reset_index(inplace=True)\n",
    "df.rename(columns={'level_0': '姓名', 'level_1': '学期'}, inplace=True)\n",
    "df"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 55,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th>语文</th>\n",
       "      <th>数学</th>\n",
       "      <th>Python</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>姓名</th>\n",
       "      <th>学期</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th rowspan=\"2\" valign=\"top\">Michal</th>\n",
       "      <th>Mid</th>\n",
       "      <td>63</td>\n",
       "      <td>61</td>\n",
       "      <td>85</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>End</th>\n",
       "      <td>133</td>\n",
       "      <td>71</td>\n",
       "      <td>27</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th rowspan=\"2\" valign=\"top\">Kobe</th>\n",
       "      <th>Mid</th>\n",
       "      <td>133</td>\n",
       "      <td>72</td>\n",
       "      <td>132</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>End</th>\n",
       "      <td>60</td>\n",
       "      <td>115</td>\n",
       "      <td>15</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th rowspan=\"2\" valign=\"top\">James</th>\n",
       "      <th>Mid</th>\n",
       "      <td>146</td>\n",
       "      <td>128</td>\n",
       "      <td>129</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>End</th>\n",
       "      <td>10</td>\n",
       "      <td>110</td>\n",
       "      <td>9</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "             语文   数学  Python\n",
       "姓名     学期                   \n",
       "Michal Mid   63   61      85\n",
       "       End  133   71      27\n",
       "Kobe   Mid  133   72     132\n",
       "       End   60  115      15\n",
       "James  Mid  146  128     129\n",
       "       End   10  110       9"
      ]
     },
     "execution_count": 55,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df.set_index(['姓名', '学期'])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 创建多层列索引"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 56,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead tr th {\n",
       "        text-align: left;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr>\n",
       "      <th></th>\n",
       "      <th colspan=\"2\" halign=\"left\">Michal</th>\n",
       "      <th colspan=\"2\" halign=\"left\">Kobe</th>\n",
       "      <th colspan=\"2\" halign=\"left\">James</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th></th>\n",
       "      <th>Mid</th>\n",
       "      <th>End</th>\n",
       "      <th>Mid</th>\n",
       "      <th>End</th>\n",
       "      <th>Mid</th>\n",
       "      <th>End</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>语文</th>\n",
       "      <td>4</td>\n",
       "      <td>117</td>\n",
       "      <td>115</td>\n",
       "      <td>66</td>\n",
       "      <td>33</td>\n",
       "      <td>7</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>数学</th>\n",
       "      <td>34</td>\n",
       "      <td>10</td>\n",
       "      <td>54</td>\n",
       "      <td>149</td>\n",
       "      <td>17</td>\n",
       "      <td>118</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Python</th>\n",
       "      <td>42</td>\n",
       "      <td>143</td>\n",
       "      <td>135</td>\n",
       "      <td>144</td>\n",
       "      <td>109</td>\n",
       "      <td>49</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "       Michal      Kobe      James     \n",
       "          Mid  End  Mid  End   Mid  End\n",
       "语文          4  117  115   66    33    7\n",
       "数学         34   10   54  149    17  118\n",
       "Python     42  143  135  144   109   49"
      ]
     },
     "execution_count": 56,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df = pd.DataFrame(np.random.randint(0, 150, size=(3,6)), index=['语文', '数学', 'Python'], columns=pd.MultiIndex.from_product([['Michal','Kobe','James'],['Mid','End']]))\n",
    "df"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 索引赋值和交换"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 57,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead tr th {\n",
       "        text-align: left;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th colspan=\"2\" halign=\"left\">X</th>\n",
       "      <th>Y</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th>10</th>\n",
       "      <th>11</th>\n",
       "      <th>10</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th rowspan=\"2\" valign=\"top\">A</th>\n",
       "      <th>1</th>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>2</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>3</td>\n",
       "      <td>4</td>\n",
       "      <td>5</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th rowspan=\"2\" valign=\"top\">B</th>\n",
       "      <th>1</th>\n",
       "      <td>6</td>\n",
       "      <td>7</td>\n",
       "      <td>8</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>9</td>\n",
       "      <td>10</td>\n",
       "      <td>11</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "     X       Y\n",
       "    10  11  10\n",
       "A 1  0   1   2\n",
       "  2  3   4   5\n",
       "B 1  6   7   8\n",
       "  2  9  10  11"
      ]
     },
     "execution_count": 57,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df1=pd.DataFrame(np.arange(12).reshape(4,3),index=[list(\"AABB\"),[1,2,1,2]],columns=[list(\"XXY\"),[10,11,10]])\n",
    "df1"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 索引命名"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 58,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead tr th {\n",
       "        text-align: left;\n",
       "    }\n",
       "\n",
       "    .dataframe thead tr:last-of-type th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr>\n",
       "      <th></th>\n",
       "      <th>XY</th>\n",
       "      <th colspan=\"2\" halign=\"left\">X</th>\n",
       "      <th>Y</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th></th>\n",
       "      <th>sum</th>\n",
       "      <th>10</th>\n",
       "      <th>11</th>\n",
       "      <th>10</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>AB</th>\n",
       "      <th>num</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th rowspan=\"2\" valign=\"top\">A</th>\n",
       "      <th>1</th>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>2</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>3</td>\n",
       "      <td>4</td>\n",
       "      <td>5</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th rowspan=\"2\" valign=\"top\">B</th>\n",
       "      <th>1</th>\n",
       "      <td>6</td>\n",
       "      <td>7</td>\n",
       "      <td>8</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>9</td>\n",
       "      <td>10</td>\n",
       "      <td>11</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "XY      X       Y\n",
       "sum    10  11  10\n",
       "AB num           \n",
       "A  1    0   1   2\n",
       "   2    3   4   5\n",
       "B  1    6   7   8\n",
       "   2    9  10  11"
      ]
     },
     "execution_count": 58,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df1.columns.names=['XY','sum']\n",
    "df1.index.names=['AB','num']\n",
    "df1"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 创建MultiIndex对象再作为索引"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 59,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead tr th {\n",
       "        text-align: left;\n",
       "    }\n",
       "\n",
       "    .dataframe thead tr:last-of-type th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr>\n",
       "      <th></th>\n",
       "      <th>XY</th>\n",
       "      <th colspan=\"2\" halign=\"left\">X</th>\n",
       "      <th>Y</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th></th>\n",
       "      <th>sum</th>\n",
       "      <th>10</th>\n",
       "      <th>11</th>\n",
       "      <th>10</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>AB</th>\n",
       "      <th>num</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th rowspan=\"2\" valign=\"top\">A</th>\n",
       "      <th>3</th>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>2</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>3</td>\n",
       "      <td>4</td>\n",
       "      <td>5</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th rowspan=\"2\" valign=\"top\">B</th>\n",
       "      <th>3</th>\n",
       "      <td>6</td>\n",
       "      <td>7</td>\n",
       "      <td>8</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>9</td>\n",
       "      <td>10</td>\n",
       "      <td>11</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "XY      X       Y\n",
       "sum    10  11  10\n",
       "AB num           \n",
       "A  3    0   1   2\n",
       "   4    3   4   5\n",
       "B  3    6   7   8\n",
       "   4    9  10  11"
      ]
     },
     "execution_count": 59,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df1.index=pd.MultiIndex.from_arrays([list(\"AABB\"),[3,4,3,4]],names=[\"AB\",\"num\"])\n",
    "df1"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 索引交换"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 60,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead tr th {\n",
       "        text-align: left;\n",
       "    }\n",
       "\n",
       "    .dataframe thead tr:last-of-type th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr>\n",
       "      <th></th>\n",
       "      <th>XY</th>\n",
       "      <th colspan=\"2\" halign=\"left\">X</th>\n",
       "      <th>Y</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th></th>\n",
       "      <th>sum</th>\n",
       "      <th>10</th>\n",
       "      <th>11</th>\n",
       "      <th>10</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>num</th>\n",
       "      <th>AB</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <th>A</th>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>2</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <th>A</th>\n",
       "      <td>3</td>\n",
       "      <td>4</td>\n",
       "      <td>5</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <th>B</th>\n",
       "      <td>6</td>\n",
       "      <td>7</td>\n",
       "      <td>8</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <th>B</th>\n",
       "      <td>9</td>\n",
       "      <td>10</td>\n",
       "      <td>11</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "XY      X       Y\n",
       "sum    10  11  10\n",
       "num AB           \n",
       "3   A   0   1   2\n",
       "4   A   3   4   5\n",
       "3   B   6   7   8\n",
       "4   B   9  10  11"
      ]
     },
     "execution_count": 60,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df1.swaplevel('AB','num')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "reorder_levels方法（多层交换）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 61,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead tr th {\n",
       "        text-align: left;\n",
       "    }\n",
       "\n",
       "    .dataframe thead tr:last-of-type th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr>\n",
       "      <th></th>\n",
       "      <th>XY</th>\n",
       "      <th colspan=\"2\" halign=\"left\">X</th>\n",
       "      <th>Y</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th></th>\n",
       "      <th>sum</th>\n",
       "      <th>10</th>\n",
       "      <th>11</th>\n",
       "      <th>10</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>AB</th>\n",
       "      <th>num</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th rowspan=\"2\" valign=\"top\">A</th>\n",
       "      <th>3</th>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>2</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>3</td>\n",
       "      <td>4</td>\n",
       "      <td>5</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th rowspan=\"2\" valign=\"top\">B</th>\n",
       "      <th>3</th>\n",
       "      <td>6</td>\n",
       "      <td>7</td>\n",
       "      <td>8</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>9</td>\n",
       "      <td>10</td>\n",
       "      <td>11</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "XY      X       Y\n",
       "sum    10  11  10\n",
       "AB num           \n",
       "A  3    0   1   2\n",
       "   4    3   4   5\n",
       "B  3    6   7   8\n",
       "   4    9  10  11"
      ]
     },
     "execution_count": 61,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df1.reorder_levels(['AB','num'],axis=0).sort_index().head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 获取索引值"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 62,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th>语文</th>\n",
       "      <th>数学</th>\n",
       "      <th>Python</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th rowspan=\"2\" valign=\"top\">Michal</th>\n",
       "      <th>Mid</th>\n",
       "      <td>7</td>\n",
       "      <td>139</td>\n",
       "      <td>95</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>End</th>\n",
       "      <td>137</td>\n",
       "      <td>68</td>\n",
       "      <td>58</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th rowspan=\"2\" valign=\"top\">Kobe</th>\n",
       "      <th>Mid</th>\n",
       "      <td>50</td>\n",
       "      <td>65</td>\n",
       "      <td>80</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>End</th>\n",
       "      <td>63</td>\n",
       "      <td>112</td>\n",
       "      <td>125</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th rowspan=\"2\" valign=\"top\">James</th>\n",
       "      <th>Mid</th>\n",
       "      <td>62</td>\n",
       "      <td>101</td>\n",
       "      <td>98</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>End</th>\n",
       "      <td>30</td>\n",
       "      <td>125</td>\n",
       "      <td>91</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "             语文   数学  Python\n",
       "Michal Mid    7  139      95\n",
       "       End  137   68      58\n",
       "Kobe   Mid   50   65      80\n",
       "       End   63  112     125\n",
       "James  Mid   62  101      98\n",
       "       End   30  125      91"
      ]
     },
     "execution_count": 62,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df = pd.DataFrame(np.random.randint(0, 150, size=(6,3)), columns=['语文', '数学', 'Python'], index=pd.MultiIndex.from_product([['Michal','Kobe','James'],['Mid','End']]))\n",
    "df"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 63,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "MultiIndex([('Michal', 'Mid'),\n",
       "            ('Michal', 'End'),\n",
       "            (  'Kobe', 'Mid'),\n",
       "            (  'Kobe', 'End'),\n",
       "            ( 'James', 'Mid'),\n",
       "            ( 'James', 'End')],\n",
       "           )"
      ]
     },
     "execution_count": 63,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df.index"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 64,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Index(['Michal', 'Michal', 'Kobe', 'Kobe', 'James', 'James'], dtype='object')"
      ]
     },
     "execution_count": 64,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df.index.get_level_values(0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 65,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Index(['Mid', 'End', 'Mid', 'End', 'Mid', 'End'], dtype='object')"
      ]
     },
     "execution_count": 65,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df.index.get_level_values(1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 66,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>语文</th>\n",
       "      <th>数学</th>\n",
       "      <th>Python</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>Mid</th>\n",
       "      <td>62</td>\n",
       "      <td>101</td>\n",
       "      <td>98</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>End</th>\n",
       "      <td>30</td>\n",
       "      <td>125</td>\n",
       "      <td>91</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "     语文   数学  Python\n",
       "Mid  62  101      98\n",
       "End  30  125      91"
      ]
     },
     "execution_count": 66,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df.loc['James', :]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 67,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th>语文</th>\n",
       "      <th>数学</th>\n",
       "      <th>Python</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th rowspan=\"2\" valign=\"top\">Michal</th>\n",
       "      <th>Mid</th>\n",
       "      <td>7</td>\n",
       "      <td>139</td>\n",
       "      <td>95</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>End</th>\n",
       "      <td>137</td>\n",
       "      <td>68</td>\n",
       "      <td>58</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "             语文   数学  Python\n",
       "Michal Mid    7  139      95\n",
       "       End  137   68      58"
      ]
     },
     "execution_count": 67,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df[df.index.get_level_values(0) == 'Michal']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 68,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th>语文</th>\n",
       "      <th>数学</th>\n",
       "      <th>Python</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>Michal</th>\n",
       "      <th>Mid</th>\n",
       "      <td>7</td>\n",
       "      <td>139</td>\n",
       "      <td>95</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Kobe</th>\n",
       "      <th>Mid</th>\n",
       "      <td>50</td>\n",
       "      <td>65</td>\n",
       "      <td>80</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>James</th>\n",
       "      <th>Mid</th>\n",
       "      <td>62</td>\n",
       "      <td>101</td>\n",
       "      <td>98</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "            语文   数学  Python\n",
       "Michal Mid   7  139      95\n",
       "Kobe   Mid  50   65      80\n",
       "James  Mid  62  101      98"
      ]
     },
     "execution_count": 68,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df[df.index.get_level_values(1) == 'Mid']"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 数据查询"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 69,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "语文         62\n",
       "数学        101\n",
       "Python     98\n",
       "Name: (James, Mid), dtype: int32"
      ]
     },
     "execution_count": 69,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df.loc[('James', 'Mid'), :]"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.5"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": false,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": true
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
